//
//  AreaSelectViewController.swift
//  hunan_ios_ldnsm
//
//  Created by I-Q-I on 2019/5/6.
//  Copyright © 2019 I-Q-I. All rights reserved.
//

import UIKit

protocol AddressSelectChangeDelegate {
    func didAddressSelectChange(province: String, city: String, area: String)
}

class AreaSelectViewController: UIViewController {
    
    var delegate: AddressSelectChangeDelegate?
    
    //选择器
    var pickerView:UIPickerView!
    
    //所以地址数据集合
    var addressArray = [[String: AnyObject]]()
    
    //选择的省索引
    var provinceIndex = 0
    //选择的市索引
    var cityIndex = 0
    //选择的县索引
    var areaIndex = 0

    fileprivate var overVeiw = UIView()
    
    required init() {
        super.init(nibName: nil, bundle: nil)
        view.backgroundColor = UIColor.clear
        self.providesPresentationContextTransitionStyle = true
        self.definesPresentationContext = true
        self.modalPresentationStyle = .custom
        
        // 初始化UI
        //        setupUIViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        UIView.animate(withDuration: 0.25) {
            self.overVeiw.alpha = 0.5
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //初始化数据
        let path = Bundle.main.path(forResource: "address", ofType:"plist")
        self.addressArray = NSArray(contentsOfFile: path!) as! Array
    }
}

// MARK: 初始化UI
extension AreaSelectViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    
    
    func setupUIViews() {
        
        overVeiw = UIView()
        overVeiw.backgroundColor = UIColor.black
        overVeiw.alpha = 0.0
        view.addSubview(overVeiw)
        
        overVeiw.snp.makeConstraints {
            $0.width.equalTo(screenWidth)
            $0.height.equalTo(screenHeight)
        }
        
        
        
        //创建选择器
        pickerView=UIPickerView()
        pickerView.backgroundColor = UIColor.white
        //将dataSource设置成自己
        pickerView.dataSource=self
        //将delegate设置成自己
        pickerView.delegate=self
        view.addSubview(pickerView)
        pickerView.snp.makeConstraints {
            $0.width.equalTo(screenWidth)
            $0.height.equalTo(250)
            $0.bottom.equalToSuperview()
        }
        
        let topView = UIView()
        topView.backgroundColor = UIColor.white
        view.addSubview(topView)
        topView.snp.makeConstraints {
            $0.width.equalToSuperview()
            $0.height.equalTo(40)
            $0.bottom.equalTo(pickerView.snp.top)
        }
        
        //建立一个按钮，触摸按钮时获得选择框被选择的索引
        let button = UIButton()
        button.setTitle("确定",for:.normal)
        button.addTarget(self, action:#selector(self.getPickerViewValue), for: .touchUpInside)
        button.setTitleColor(UIColor.black, for: .normal)
        topView.addSubview(button)
        button.snp.makeConstraints {
            $0.width.equalTo(100)
            $0.height.equalTo(30)
            $0.top.equalToSuperview().offset(10)
            $0.right.equalToSuperview().offset(-10)
        }
    }
    
    //设置选择框的列数为3列,继承于UIPickerViewDataSource协议
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    
    //设置选择框的行数，继承于UIPickerViewDataSource协议
    func pickerView(_ pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return self.addressArray.count
        } else if component == 1 {
            let province = self.addressArray[provinceIndex]
            return province["cities"]!.count
        } else {
            let province = self.addressArray[provinceIndex]
            if let city = (province["cities"] as! NSArray)[cityIndex]
                as? [String: AnyObject] {
                return city["areas"]!.count
            } else {
                return 0
            }
        }
    }
    
    //设置选择框各选项的内容，继承于UIPickerViewDelegate协议
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,
                    forComponent component: Int) -> String? {
        if component == 0 {
            return self.addressArray[row]["state"] as? String
        }else if component == 1 {
            let province = self.addressArray[provinceIndex]
            let city = (province["cities"] as! NSArray)[row]
                as! [String: AnyObject]
            return city["city"] as? String
        }else {
            let province = self.addressArray[provinceIndex]
            let city = (province["cities"] as! NSArray)[cityIndex]
                as! [String: AnyObject]
            return (city["areas"] as! NSArray)[row] as? String
        }
    }
    
    //选中项改变事件（将在滑动停止后触发）
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int,
                    inComponent component: Int) {
        //根据列、行索引判断需要改变数据的区域
        switch (component) {
        case 0:
            provinceIndex = row;
            cityIndex = 0;
            areaIndex = 0;
            pickerView.reloadComponent(1);
            pickerView.reloadComponent(2);
            pickerView.selectRow(0, inComponent: 1, animated: false)
            pickerView.selectRow(0, inComponent: 2, animated: false)
        case 1:
            cityIndex = row;
            areaIndex = 0;
            pickerView.reloadComponent(2);
            pickerView.selectRow(0, inComponent: 2, animated: false)
        case 2:
            areaIndex = row;
        default:
            break;
        }
    }
    
    //触摸按钮时，获得被选中的索引
    @objc func getPickerViewValue(){
        //获取选中的省
        let p = self.addressArray[provinceIndex]
        let province = p["state"]!
        
        //获取选中的市
        let c = (p["cities"] as! NSArray)[cityIndex] as! [String: AnyObject]
        let city = c["city"] as! String
        
        //获取选中的县（地区）
        var area = ""
        if (c["areas"] as! [String]).count > 0 {
            area = (c["areas"] as! [String])[areaIndex]
        }
        self.dismiss(animated: false, completion: nil)
        self.delegate?.didAddressSelectChange(province: "\(province)", city: "\(city)", area: "\(area)")
    }
}

// MARK: 点击屏幕弹出退出
extension AreaSelectViewController {
    
    func sheetViewDismiss() {
        UIView.animate(withDuration: 0.25, animations: {
            self.overVeiw.alpha = 0
        }) { (_) in
            self.dismiss(animated: false, completion: nil)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        sheetViewDismiss()
    }
    
    @objc func cancelBtnDidClick(btn: UIButton) {
        sheetViewDismiss()
    }
}
